#!/usr/bin/env python
#
# Symbol table for the SLDT example language
#
# Author:   Mike Murphy <mamurph@cs.clemson.edu>
# Revision: 7 January 2009
#
# Copyright 2008-2009 Clemson University
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# This material is based upon work supported under a National Science
# Foundation Graduate Research Fellowship. Any opinions, findings,
# conclusions or recommendations expressed in this publication are those of
# the author(s) and do not necessarily reflect the views of the National
# Science Foundation.


# For a language as simple as SLDT, a dictionary could be used directly (in
# place of a symbol table class). However, a custom class might be a better
# design decision for a more complex language with variables and scopes....
class SymbolTable(object):
   def __init__(self, preload = {}):
      self.contents = {}
      for key in preload:
         self.contents[key] = preload[key]
   def __contains__(self, item):
      return item in self.contents
   def __getitem__(self, key):
      return self.contents[key]
   def __setitem__(self, key, value):
      self.contents[key] = value
   def getValue(self, symbol):
      value = None
      if symbol in self.contents:
         value = self.contents[symbol]
      return value
   def newConstant(self, symbol, value):
      success = False
      if symbol not in self.contents:
         self.contents[symbol] = value
         success = True
      return success
   def __repr__(self):
      return str(self.contents)
#

if __name__ == '__main__':
   st = SymbolTable()
   print st
   print st.getValue('non-existent')
   st.newConstant('TRUE', 42)
   st.newConstant('FALSE', 0)
   print st.newConstant('True', -42)
   print st.newConstant('TRUE', -50)
   print st
   print 'False' in st
#
